﻿using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace CloudShot.Controls
{
  public enum SplitButtonAppearance
  {
    SplitButton,
    DropDownButton
  }

  public class SplitButton : Button
  {
    [DefaultValue(null)]
    public ContextMenuStrip Menu { get; set; }

    public Color SplitColor { get; set; }

    [DefaultValue(15)]
    public int SplitSize { get; set; }

    private int SplitAreaX
    {
      get { return ClientRectangle.Width - SplitSize; }
    }

    [DefaultValue(SplitButtonAppearance.SplitButton)]
    public SplitButtonAppearance Appearance { get; set; }

    public SplitButton()
    {
      Appearance  = SplitButtonAppearance.SplitButton;
      SplitSize = 15;
    }

    protected override void OnMouseDown(MouseEventArgs mevent)
    {
      if (Menu != null && mevent.Button == MouseButtons.Left && InSplitArea(mevent.X))
      {
        Menu.Show(this, new Point(0, Height));
      }
      else
      {
        base.OnMouseDown(mevent);
      }
    }

    protected override void OnMouseUp(MouseEventArgs mevent)
    {
      if (Menu != null && mevent.Button == MouseButtons.Left && InSplitArea(mevent.X))
        return;

      base.OnMouseUp(mevent);
    }

    protected override void OnPaint(PaintEventArgs pevent)
    {
      base.OnPaint(pevent);

      int arrowX = ClientRectangle.Width - (SplitSize - (SplitSize - 7) / 2);
      int arrowY = ClientRectangle.Height / 2 - 1;

      Brush brush = Enabled ? SystemBrushes.ControlText : SystemBrushes.ButtonShadow;

      Point[] arrows = {
        new Point(arrowX, arrowY),
        new Point(arrowX + 7, arrowY),
        new Point(arrowX + 3, arrowY + 4)
      };

      Graphics graphics = pevent.Graphics;

      graphics.FillPolygon(brush, arrows);
      graphics.DrawLine(new Pen(SplitColor), SplitAreaX, 0, SplitAreaX, ClientRectangle.Height);
    }

    private bool InSplitArea(int x)
    {
      if (Appearance == SplitButtonAppearance.DropDownButton)
        return true;

      return x >= SplitAreaX && x <= ClientRectangle.Width;
    }
  }
}